<template>
  <view class="page-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="header-content">
        <view class="back-icon" @click="goBack">
          <uni-icons type="left" size="20" color="#fff"></uni-icons>
        </view>
        <view class="search-input-wrapper" @click="navigateToSearch">
          <view class="search-box">
            <view class="search-icon">
              <uni-icons type="search" size="16" color="#e84d1c"></uni-icons>
            </view>
            <view class="search-text text-ellipsis">{{ keyword || '请搜索商品' }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选导航栏 -->
    <view class="filter-navbar">
      <view class="filter-item" :class="{active: filterIndex === 0}" @click="tabClick(0)">
        <text>综合排序</text>
        <view class="active-line" v-if="filterIndex === 0"></view>
          </view>
      <view class="filter-item" :class="{active: filterIndex === 1}" @click="tabClick(1)">
        <text>销量优先</text>
        <view class="active-line" v-if="filterIndex === 1"></view>
          </view>
      <view class="filter-item price-item" :class="{active: filterIndex === 2}" @click="tabClick(2)">
            <text>价格</text>
        <view class="price-arrows">
          <text class="arrow-up" :class="{active: filterIndex === 2 && priceOrder === 1}">↑</text>
          <text class="arrow-down" :class="{active: filterIndex === 2 && priceOrder === 2}">↓</text>
        </view>
        <view class="active-line" v-if="filterIndex === 2"></view>
      </view>
      <view class="filter-item category-btn" @click="toggleCateMask('show')">
        <uni-icons type="bars" size="22" color="#666"></uni-icons>
      </view>
    </view>

    <!-- 加载状态显示 -->
    <view class="loading-container" v-if="isLoading">
      <view class="loading-spinner">
        <view class="loading-bounce"></view>
      </view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 商品列表 -->
    <scroll-view 
      v-else
      class="goods-container" 
      scroll-y 
      enable-back-to-top
      :scroll-top="scrollTop"
      :scroll-into-view="scrollIntoView"
      @scrolltolower="onReachBottom"
      @refresherrefresh="onPullDownRefresh"
      @scroll="onScroll"
      refresher-enabled
      :refresher-triggered="refreshing"
    >
      <!-- 添加顶部锚点元素 -->
      <view id="top" class="scroll-top-anchor"></view>
      
      <view class="goods-list">
        <view
          v-for="(item, index) in goodsList" 
          :key="index"
            class="goods-item"
            @click="navToDetailPage(item)"
        >
          <view class="goods-item-inner">
          <view class="image-wrapper">
              <view class="album-container">
                <album :images="item.album" :showExtraImages="false" height="100%" width="100%"></album>
              </view>
          </view>
            <view class="goods-info">
              <text class="goods-title">{{ item.productName }}</text>
              <text class="goods-subtitle" v-if="item.subtitle">{{ item.subtitle }}</text>
          <view class="price-box">
                <view class="price">
                  <text class="symbol">¥</text>
                  <text class="amount">{{ item.sellingPrice }}</text>
                  <text class="unit">起</text>
                </view>
                <text class="sold-count">已售 {{ item.saleCount || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="load-more" v-if="goodsList.length > 0">
      <uni-load-more :status="loadingType"></uni-load-more>
      </view>
      
      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="goodsList.length === 0 && loadingType !== 'loading'">
        <uni-icons type="shop" size="50" color="#ddd"></uni-icons>
        <text>暂无相关商品</text>
      </view>
    </scroll-view>

    <!-- 回到顶部按钮 -->
    <view 
      class="back-to-top" 
      :class="{'show': showBackToTop}"
      @click="scrollToTop"
    >
      <uni-icons type="top" size="20" color="#fff"></uni-icons>
    </view>

    <!-- 分类侧边栏 -->
    <view 
      class="category-mask" 
      :class="{'show': cateMaskState === 1, 'hide': cateMaskState === 2}"
      @click="toggleCateMask"
    >
      <view 
        class="category-panel" 
        :class="{'show': cateMaskState === 1, 'hide': cateMaskState === 2}"
        @click.stop
      >
        <view class="category-header">
          <text class="title">商品分类</text>
          <view class="close-btn" @click="toggleCateMask">
            <uni-icons type="close" size="16" color="#999"></uni-icons>
          </view>
        </view>
        
        <scroll-view scroll-y class="category-content">
          <view 
            v-for="item in cateList" 
            :key="item.id" 
            class="category-section"
          >
            <view class="parent-category">{{ item.categoryName }}</view>
            <view class="sub-categories">
              <view
                v-for="subItem in item.children" 
                :key="subItem.id"
                class="sub-category-item" 
                :class="{'active': subItem.id == cateId}"
                @click="changeCate(subItem)"
              >
                {{ subItem.categoryName }}
              </view>
              </view>
            </view>
          </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
import {listProduct} from "@/api/sell/product";
import {listProductCategory} from "@/api/sell/productCategory";
import Album from "@/components/album/index.vue";
import Navbar from "@/components/navbar/index.vue";
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";

export default {
  components: {
    UniIcons,
    Navbar,
    uniLoadMore, 
    Album
  },
  data() {
    return {
      keyword: '',
      cateMaskState: 0, // 0: hidden, 1: show, 2: animating
      loadingType: 'more', // more, loading, nomore
      filterIndex: 0, // 0: comprehensive, 1: sales, 2: price
      cateId: 0, // selected category id
      priceOrder: 0, // 0: default, 1: price low to high, 2: price high to low
      cateList: [],
      goodsList: [],
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      fromSearch: false,
      statusBarHeight: 20,
      refreshing: false,
      showBackToTop: false, // 是否显示回到顶部按钮
      scrollTop: 0, // 滚动距离
      scrollIntoView: '', // 用于滚动到指定元素
      isLoading: true, // 页面加载状态
    };
  },

  onLoad(options) {
    // 设置参数
    this.cateId = options.categoryId || 0;
    this.keyword = options.keyword || '';

    // 检查是否从搜索页面导航过来
    let pages = getCurrentPages();
    if (pages.length > 1) {
      let prevPageRoute = pages[pages.length - 2].route;
      this.fromSearch = prevPageRoute === 'pages/sellment/search/search';
    }

    // 获取状态栏高度
    this.getStatusBarHeight();
    
    // 加载分类列表
    this.loadCateList();
    
    // 设置加载状态并加载数据
    this.isLoading = true;
    setTimeout(() => {
      this.loadData()
        .finally(() => {
          this.isLoading = false;
        });
    }, 500);
  },
  
  methods: {
    // Get status bar height
    getStatusBarHeight() {
      uni.getSystemInfo({
        success: (res) => {
          this.statusBarHeight = res.statusBarHeight;
        }
      });
    },
    
    // Navigate back
    goBack() {
      uni.navigateBack();
    },
    
    // Navigate to search page
    navigateToSearch() {
      if (this.fromSearch) {
        uni.navigateBack({
          delta: 1
        });
      } else {
        uni.navigateTo({
          url: '/pages/sellment/search/search'
        });
      }
    },
    
    // Load categories
    async loadCateList() {
      try {
      let {data} = await listProductCategory({isVisible: 1});
      this.cateList = data;
      } catch (error) {
        console.error('Failed to load categories:', error);
        uni.showToast({
          title: '分类加载失败',
          icon: 'none'
        });
      }
    },
    
    // Load products
    async loadData(type = 'add', loading) {
      // Return if no more data
      if (type === 'add') {
        if (this.loadingType === 'nomore') {
          return;
        }
        this.loadingType = 'loading';
      } else {
        this.loadingType = 'more';
        this.refreshing = true;
      }

      try {
        // Prepare query params
      const queryParams = {
        categoryId: this.cateId,
        onShelf: 1,
        pageNum: type === 'add' ? this.page.pageNum++ : 1,
        pageSize: this.page.pageSize,
        keyword: this.keyword
      };
        
        // Add sort parameters
      if (this.filterIndex === 1) {
        queryParams.sortBy = 'sale_count';
        queryParams.ascending = false;
      }
      if (this.filterIndex === 2) {
        queryParams.sortBy = 'selling_price';
          queryParams.ascending = this.priceOrder === 1;
        }
        
        // Fetch data
      let {rows: goodsList, total} = await listProduct(queryParams);
        
        // Reset list on refresh
      if (type === 'refresh') {
        this.page.pageNum = 1;
        this.goodsList = [];
      }

        // Append new data - 只添加一次数据而不是多次重复
      this.goodsList = this.goodsList.concat(goodsList);

        // Check if there's more data
      this.loadingType = this.goodsList.length >= total ? 'nomore' : 'more';
        
      } catch (error) {
        console.error('Failed to load products:', error);
        uni.showToast({
          title: '商品加载失败',
          icon: 'none'
        });
      } finally {
        // Complete loading
      if (type === 'refresh') {
          this.refreshing = false;
          if (loading) {
            uni.hideLoading();
          }
        }
      }
    },
    
    // Tab filter click
    tabClick(index) {
      if (this.filterIndex === index && index !== 2) {
        return;
      }
      
      this.filterIndex = index;
      
      if (index === 2) {
        this.priceOrder = this.priceOrder === 1 ? 2 : 1;
      } else {
        this.priceOrder = 0;
      }
      
      this.scrollToTop();
      
      this.loadData('refresh', true);
      uni.showLoading({
        title: '正在加载'
      });
    },
    
    // Toggle category panel
    toggleCateMask(type) {
      if (type === 'show') {
        this.cateMaskState = 1;
      } else {
      this.cateMaskState = 2;
      setTimeout(() => {
          this.cateMaskState = 0;
        }, 300);
      }
    },
    
    // Category selection
    changeCate(item) {
      this.cateId = item.id;
      this.toggleCateMask();
      
      this.scrollToTop();
      
      this.loadData('refresh', true);
      uni.showLoading({
        title: '正在加载'
      });
    },
    
    // Navigate to product detail
    navToDetailPage(product) {
      uni.navigateTo({
        url: `/pages/sellment/product/product?id=${product.id}`
      });
    },
    
    // Handle pull down refresh
    onPullDownRefresh() {
      this.loadData('refresh');
    },
    
    // Handle reach bottom
    onReachBottom() {
      this.loadData();
    },
    
    // 监听滚动事件
    onScroll(e) {
      // 当滚动距离超过一定值时显示回到顶部按钮
      if (e.detail.scrollTop > 300) {
        this.showBackToTop = true;
      } else {
        this.showBackToTop = false;
      }
    },
    
    // 回到顶部
    scrollToTop() {
      // 获取当前滚动位置
      uni.createSelectorQuery()
        .in(this)
        .select('.goods-container')
        .scrollOffset(data => {
          if (!data) return;
          
          const currentScrollTop = data.scrollTop;
          if (currentScrollTop <= 0) return; // 已经在顶部，无需滚动
          
          // 计算动画步数和时长
          const duration = 400; // 总动画时长(毫秒)
          const steps = 20; // 动画分为多少步
          const interval = duration / steps; // 每步时间间隔
          const scrollStep = currentScrollTop / steps; // 每步滚动距离
          
          // 执行平滑滚动动画
          let currentStep = 0;
          const smoothScroll = () => {
            currentStep++;
            if (currentStep >= steps) {
              // 最后一步，确保滚动到顶部
              this.scrollTop = 0;
              this.scrollIntoView = 'top';
              return;
            }
            
            // 计算当前步应滚动到的位置
            const targetScrollTop = currentScrollTop - (scrollStep * currentStep);
            this.scrollTop = targetScrollTop;
            
            // 继续下一步动画
            setTimeout(smoothScroll, interval);
          };
          
          // 开始动画
          setTimeout(smoothScroll, 0);
        })
        .exec();
    }
  }
}
</script>

<style lang="scss" scoped>
// 通用文本省略样式
.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  overflow: hidden;
}

/* Status bar */
.status-bar {
  background: linear-gradient(180deg, #e84d1c 0%, #f06e44 100%);
  width: 100%;
  flex-shrink: 0;
}

/* Search header */
.search-header {
  background: linear-gradient(180deg, #e84d1c 0%, #f06e44 100%);
  padding: 15rpx 0 20rpx 0;
  z-index: 99;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
  
  .header-content {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
  }
  
  .back-icon {
    width: 50rpx;
    height: 50rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  
  .search-input-wrapper {
    flex: 1;
    margin-left: 10rpx;
  }
  
  .search-box {
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 40rpx;
    padding: 0 30rpx;
    height: 66rpx;
    box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.05);
  }
  
  .search-icon {
    width: 36rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12rpx;
  }
  
  .search-text {
    color: #999;
    font-size: 26rpx;
    flex: 1;
    line-height: 1;
  }
}

/* Filter navbar */
.filter-navbar {
  display: flex;
  height: 84rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  z-index: 98;
  margin-bottom: 2rpx;
  flex-shrink: 0;
  
  .filter-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    font-size: 28rpx;
    color: #666;

    &.active {
      color: #e84d1c;
      font-weight: 500;
    }
    
    &.price-item {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .active-line {
        position: absolute;
      bottom: 0;
        left: 50%;
        transform: translateX(-50%);
      width: 64rpx;
      height: 4rpx;
      background-color: #e84d1c;
    }
    
    .price-arrows {
      display: flex;
      align-items: center;
      margin-left: 6rpx;
      
      .arrow-up, .arrow-down {
        font-size: 20rpx;
        color: #ccc;
        line-height: 1;
        margin: 0 1rpx;
        
        &.active {
          color: #e84d1c;
        }
      }
    }
    
    &.category-btn {
      flex: 0.5;
    }
  }
}

/* Goods container */
.goods-container {
  flex: 1;
  width: 100%;
  height: calc(100vh - 270rpx);
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* Load more */
.load-more {
  padding: 20rpx 0 40rpx;
}

/* Goods list */
.goods-list {
  display: flex;
  flex-wrap: wrap;
  padding: 16rpx;
  
  .goods-item {
    width: 49%;
    margin-bottom: 16rpx;
    box-sizing: border-box;
    animation: slideUp 0.5s ease-out;
    opacity: 0;
    animation-fill-mode: forwards;
    
    @for $i from 1 through 10 {
      &:nth-child(#{$i}) {
        animation-delay: #{$i * 0.05}s;
      }
    }
    
    &:nth-child(odd) {
      margin-right: 2%;
  }

    .goods-item-inner {
      background-color: #fff;
      overflow: hidden;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      transition: all 0.2s;
      height: 100%;
    display: flex;
    flex-direction: column;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.03);
      }
    }
    
    .image-wrapper {
      width: 100%;
      height: 330rpx;
      overflow: hidden;
      position: relative;
      border-radius: 12rpx 12rpx 0 0;
      background-color: #f9f9f9;
      display: flex;
    }
    
    .goods-info {
      padding: 18rpx;
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    
    .goods-title {
      font-size: 28rpx;
      color: #333;
      line-height: 1.4;
      display: block;
      margin-bottom: 6rpx;
      font-weight: 500;
      /* Allow for two lines of text with ellipsis */
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      height: 2.8em;
    }
    
    .goods-subtitle {
      font-size: 24rpx;
      color: #888;
      line-height: 1.4;
      display: block;
      margin-top: 4rpx;
      margin-bottom: 8rpx;
    }
    
    .price-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: auto;
      padding-top: 10rpx;
    }
    
    .price {
      display: flex;
      align-items: baseline;
      color: #e84d1c;
      
      .symbol {
        font-size: 24rpx;
      }
      
      .amount {
        font-size: 32rpx;
        font-weight: 500;
      }
      
      .unit {
        font-size: 22rpx;
        color: #999;
        margin-left: 2rpx;
      }
    }
    
    .sold-count {
      font-size: 22rpx;
      color: #999;
      background-color: #f8f8f8;
      padding: 4rpx 10rpx;
      border-radius: 20rpx;
    }
  }
}

/* 修复Album组件中图片右侧不贴边的问题 */
:deep(.image-list) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.image-box) {
  width: 100% !important;
  height: 100% !important;
  margin-right: 0 !important;
  border-radius: 12rpx 12rpx 0 0 !important;
    }

:deep(image) {
  border-radius: 12rpx 12rpx 0 0;
  width: 100% !important;
  height: 100% !important;
  object-fit: cover !important;
}

/* Empty tip */
.empty-tip {
    display: flex;
  flex-direction: column;
  align-items: center;
    justify-content: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
  
  text {
    margin-top: 20rpx;
  }
}

/* Category sidebar */
.category-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s;

  &.show {
    opacity: 1;
    visibility: visible;
  }
  
  &.hide {
    opacity: 0;
    visibility: hidden;
  }
}

.category-panel {
  position: fixed;
  top: 0;
  right: 0;
  width: 75%;
  height: 100%;
  background-color: #fff;
  z-index: 101;
  transform: translateX(100%);
  transition: all 0.3s;
  display: flex;
  flex-direction: column;
  border-radius: 16rpx 0 0 16rpx;
  overflow: hidden;
  
  &.show {
    transform: translateX(0);
  }
  
  &.hide {
    transform: translateX(100%);
  }
  
  .category-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f2f2f2;
    
    .title {
      font-size: 30rpx;
      font-weight: 600;
      color: #333;
    }
    
    .close-btn {
      width: 50rpx;
      height: 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .category-content {
    flex: 1;
    overflow-y: auto;
    
    .category-section {
      margin-bottom: 20rpx;
    }
    
    .parent-category {
      padding: 20rpx 30rpx;
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      background-color: #f8f8f8;
  }

    .sub-categories {
      display: flex;
      flex-wrap: wrap;
      padding: 15rpx;
    }
    
    .sub-category-item {
      width: 50%;
      padding: 15rpx;
      font-size: 26rpx;
      color: #666;
      box-sizing: border-box;
      
      &.active {
        color: #e84d1c;
        font-weight: 500;
  }
    }
  }
}

.album-container {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  overflow: hidden;
}

/* 回到顶部按钮 */
.back-to-top {
  position: fixed;
  right: 30rpx;
  bottom: 120rpx;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #FF7B00, #FF6B00);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(255, 107, 0, 0.3);
  z-index: 90;
  opacity: 0;
  transform: translateY(100rpx);
  transition: all 0.3s ease;
  
  &.show {
    opacity: 1;
    transform: translateY(0);
  }
  
  &:active {
    transform: translateY(0) scale(0.95);
    box-shadow: 0 2rpx 8rpx rgba(255, 107, 0, 0.2);
    }
  }

/* 顶部锚点元素 */
.scroll-top-anchor {
  height: 0;
    width: 100%;
  visibility: hidden;
}

/* 加载动画样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 190rpx);
  animation: fadeIn 0.5s ease-out;
  
  .loading-spinner {
    width: 80rpx;
    height: 80rpx;
    position: relative;
    margin-bottom: 20rpx;
    
    .loading-bounce {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: rgba(232, 77, 28, 0.6);
      opacity: 0.6;
      position: absolute;
      top: 0;
      left: 0;
      animation: bounce 2s infinite ease-in-out;
      
      &:before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-color: rgba(232, 77, 28, 0.6);
        opacity: 0.6;
        animation: bounce 2s infinite ease-in-out;
        animation-delay: -1.0s;
      }
    }
  }
  
  .loading-text {
    color: #999;
    font-size: 28rpx;
  }
}

@keyframes bounce {
  0%, 100% { 
    transform: scale(0);
  }
  50% { 
    transform: scale(1.0);
  }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0;
    transform: translateY(20rpx);
    }
  to { 
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
